// 定义主要指数列表，包含各个指数的代码和名称
const INDEX_LIST = [
  { code: 'sh000001', name: '上证指数' },
  { code: 'sz399001', name: '深证成指' },
  { code: 'sz399006', name: '创业板' },
  { code: 'sh000688', name: '科创50' },
  { code: 'hkHSI', name: '恒生指数' },
  { code: 'usDJI', name: '道琼斯:(DJI)' },
  { code: 'usIXIC', name: '纳斯达克:(IXIC)' }
];

// 拖拽排序相关变量
let draggedItem = null;      // 当前被拖拽的元素
let draggedItemIndex = null; // 被拖拽元素的初始索引

/**
 * 从后台服务获取股票数据
 * @param {string} code 股票代码
 * @returns {Promise} 返回股票数据的Promise
 */
async function fetchStockData(code) {
  return new Promise((resolve) => {
    chrome.runtime.sendMessage(
      { type: 'fetchStock', code: code },
      response => resolve(response)
    );
  });
}

/**
 * 搜索股票
 * @param {string} keyword 搜索关键词
 * @returns {Array} 返回搜索结果数组
 */
async function searchStock(keyword) {
  try {
    const url = `https://proxy.finance.qq.com/cgi/cgi-bin/smartbox/search?stockFlag=1&fundFlag=1&app=official_website&c=1&query=${encodeURIComponent(keyword)}`;
    console.log(url);
    const response = await fetch(url, {
      headers: {
        'Accept': '*/*',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Origin': 'https://gu.qq.com',
        'Referer': 'https://gu.qq.com/'
      }
    });
    const data = await response.json();
    const stocks = data?.stock || [];
    console.log(stocks);
    // 只取前10条结果
    const stockList = stocks.slice(0, 10).map(stock => {
      return {
        code: stock.code,
        name: stock.name
      };
    });
    return stockList;
  } catch (error) {
    console.error('搜索股票失败:', error);
    return [];
  }
}

/**
 * 从本地存储加载股票列表
 * @param {Function} callback 回调函数，参数为股票列表
 */
function loadStockList(callback) {
    chrome.storage.local.get(['stockList'], (result) => {
        callback(result.stockList || []);
    });
}

/**
 * 保存股票列表到本地存储
 * @param {Array} stockList 股票列表
 * @param {Function} callback 可选的回调函数
 */
function saveStockList(stockList, callback) {
  chrome.storage.local.set({ stockList: stockList }, () => {
    if (callback) callback();
  });
}

/**
 * 初始化设置面板
 * 包含搜索功能和添加股票功能
 */
function initSettingsPanel() {
  const settingsIcon = document.querySelector('.settings-icon');
  const settingsPanel = document.getElementById('settings-panel');
  const searchInput = document.getElementById('stock-search');
  const searchResults = document.getElementById('search-results');
  
  // 点击设置图标显示面板
  settingsIcon.addEventListener('click', () => {
    settingsPanel.style.display = 'block';
  });

  // 点击关闭按钮隐藏面板
  document.getElementById('close-settings').addEventListener('click', () => {
    settingsPanel.style.display = 'none';
    searchInput.value = '';
    searchResults.innerHTML = '';
  });

  // 搜索功能实现
  let searchTimeout;
  searchInput.addEventListener('input', (e) => {
    clearTimeout(searchTimeout);
    const keyword = e.target.value.trim();
    if (keyword) {
      // 使用延时防抖，500ms后执行搜索
      searchTimeout = setTimeout(async () => {
        const result = await searchStock(keyword);
        if (result && result.length > 0) {
          // 显示搜索结果
          searchResults.innerHTML = result.map(stock => `
            <div class="search-result-item">
              <span>${stock.name} (${stock.code})</span>
              <button class="add-stock" data-code="${stock.code}" data-name="${stock.name}">添加</button>
            </div>
          `).join('');
        } else {
          searchResults.innerHTML = '<div class="no-result">未找到股票</div>';
        }
      }, 500);
    } else {
      searchResults.innerHTML = '';
    }
  });

  // 处理添加股票的点击事件
  searchResults.addEventListener('click', (e) => {
    if (e.target.classList.contains('add-stock')) {
      const { code, name } = e.target.dataset;
      console.log('股票代码:', code);
      console.log('股票名称:', name);
      
      loadStockList((stockList) => {
        // 检查是否已存在该股票
        if (!stockList.some(stock => stock.code === code)) {
          stockList.push({ code, name });
          saveStockList(stockList);
          
          // 更新显示
          loadAndDisplayStockList();
        } else {
          alert('该股票已在列表中');
        }
      });
    }
  });
}

/**
 * 加载并显示股票列表
 */
function loadAndDisplayStockList() {
  loadStockList(async (stockList) => {
    const stockListElement = document.getElementById('stock-list');
    if (!stockListElement) return;

    stockListElement.innerHTML = '';

    // 遍历股票列表，获取每只股票的数据并显示
    for (const stock of stockList) {
      try {
        const data = await fetchStockData(stock.code);
        if (data) {
          createStockItem(stockListElement, data);
        }
      } catch (error) {
        console.error(`加载${stock.name}数据失败:`, error);
      }
    }
    
    // 初始化拖拽排序功能
    initDragAndDrop();
  });
}

/**
 * 创建股票列表项
 * @param {HTMLElement} container 容器元素
 * @param {Object} data 股票数据
 * @returns {HTMLElement} 创建的股票项元素
 */
function createStockItem(container, data) {
  const className = data.change >= 0 ? 'price-up' : 'price-down';
  const stockItem = document.createElement('div');
  stockItem.className = 'stock-item';
  stockItem.dataset.code = data.code;
  
  // 构建股票项的HTML结构
  stockItem.innerHTML = `
    <div class="stock-info">
      <div>
        <div>${data.name}</div>
        <div style="font-size: 12px; color: #666;">${data.code}</div>
      </div>
      <div style="text-align: right;">
        <div class="stock-price ${className}">${data.changePercent}%</div>
        <div class="stock-change ${className}" style="font-size: 12px;">
          ${data.change > 0 ? '+' : ''}${data.change} (${data.price})
        </div>
      </div>
    </div>
    <div class="drag-handle">
      <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#999" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
        <line x1="8" y1="6" x2="16" y2="6"></line>
        <line x1="8" y1="12" x2="16" y2="12"></line>
        <line x1="8" y1="18" x2="16" y2="18"></line>
      </svg>
    </div>
    <button class="delete-btn">×</button>
  `;

  // 添加删除按钮的点击事件
  const deleteBtn = stockItem.querySelector('.delete-btn');
  deleteBtn.addEventListener('click', function() {
    loadStockList(stockList => {
      const newStockList = stockList.filter(stock => stock.code !== data.code);
      saveStockList(newStockList, () => {
        stockItem.remove();
      });
    });
  });

  container.appendChild(stockItem);
  return stockItem;
}

/**
 * 更新所有股票的涨跌幅数据
 */
async function updateStockChanges() {
  const stockItems = document.querySelectorAll('.stock-item');
  
  for (const item of stockItems) {
    try {
      const code = item.dataset.code;
      const data = await fetchStockData(code);
      
      if (data) {
        const priceElement = item.querySelector('.stock-price');
        const changeElement = item.querySelector('.stock-change');
        const className = data.change >= 0 ? 'price-up' : 'price-down';
        
        // 更新价格和涨跌幅的样式和内容
        priceElement.className = `stock-price ${className}`;
        changeElement.className = `stock-change ${className}`;
        priceElement.textContent = data.changePercent+'%';
        changeElement.textContent = `${data.change > 0 ? '+' : ''}${data.change} (${data.price})`;
      }
    } catch (error) {
      console.log(item);
      console.error('更新股票数据失败:' + code, error);
    }
  }
}

/**
 * 更新指数数据显示
 */
async function updateUI() {
  INDEX_LIST.forEach(async (index) => {
    try {
      const data = await fetchStockData(index.code);
      if (data) {
        const element = document.getElementById(index.code);
        if (element) {
          const className = data.change >= 0 ? 'price-up' : 'price-down';
          element.innerHTML = `${data.name}<span class="${className}"><span style="font-size:16px">${data.changePercent}%</span> (${data.change})</span>`;
        }
      }
    } catch (error) {
      console.error(`更新${index.name}数据失败:`, error);
    }
  });
}

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', () => {
  // 初始化各个功能
  initSettingsPanel();
  updateUI();
  loadAndDisplayStockList();
  
  // 定时更新数据
  setInterval(updateUI, 5000);
  setInterval(() => {
    document.getElementById('current-time').textContent = new Date().toLocaleTimeString();
    updateStockChanges();
  }, 5000);

  // 导入导出功能相关元素
  const importExportIcon = document.querySelector('.import-export-icon');
  const modal = document.querySelector('.import-export-modal');
  const closeModal = document.querySelector('.close-modal');
  const exportBtn = document.getElementById('export-btn');
  const importBtn = document.getElementById('import-btn');
  const importFile = document.getElementById('import-file');

  // 导入导出模态框事件处理
  importExportIcon.addEventListener('click', () => {
    modal.style.display = 'block';
  });

  closeModal.addEventListener('click', () => {
    modal.style.display = 'none';
  });

  modal.addEventListener('click', (e) => {
    if (e.target === modal) {
      modal.style.display = 'none';
    }
  });

  // 导出功能实现
  exportBtn.addEventListener('click', async () => {
    const stocks = await chrome.storage.local.get(['stockList']);
    const stockList = stocks.stockList || [];
    
    const blob = new Blob([JSON.stringify(stockList, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    
    const a = document.createElement('a');
    a.href = url;
    a.download = 'stockList.json';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  });

  // 导入功能实现
  importBtn.addEventListener('click', async () => {
    const file = importFile.files[0];
    if (!file) {
      alert('请先选择文件');
      return;
    }

    const reader = new FileReader();
    reader.onload = async (e) => {
      try {
        const watchlist = JSON.parse(e.target.result);
        if (!Array.isArray(watchlist)) {
          throw new Error('无效的文件格式');
        }
        
        await chrome.storage.local.set({ stockList: watchlist });
        alert('导入成功！');
        location.reload();
      } catch (error) {
        alert('导入失败：' + error.message);
      }
    };
    reader.readAsText(file);
  });

  // 关于页面功能
  const aboutIcon = document.querySelector('.about-icon');
  const aboutModal = document.querySelector('.about-modal');
  const aboutCloseBtn = aboutModal.querySelector('.close-modal');
  const markdownContent = aboutModal.querySelector('.markdown-content');

  // 加载并渲染README.md
  async function loadReadme() {
    try {
      const response = await fetch(chrome.runtime.getURL('README.md'));
      const text = await response.text();
      const html = markdownToHtml(text);
      markdownContent.innerHTML = html;
    } catch (error) {
      console.error('加载 README.md 失败:', error);
      markdownContent.innerHTML = '<p>加载失败，请稍后重试。</p>';
    }
  }

  // Markdown转HTML的简单实现
  function markdownToHtml(markdown) {
    return markdown
      .replace(/^### (.*$)/gm, '<h5>$1</h5>')
      .replace(/^## (.*$)/gm, '<h4>$1</h4>')
      .replace(/^# (.*$)/gm, '<h3>$1</h3>')
      .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
      .replace(/\*(.*?)\*/g, '<em>$1</em>')
      .replace(/```([\s\S]*?)```/g, '<pre><code>$1</code></pre>')
      .replace(/`(.*?)`/g, '<code>$1</code>')
      .replace(/^\s*\d+\.\s+(.*$)/gm, '<ol><li>$1</li></ol>')
      .replace(/^\s*[\-\*]\s+(.*$)/gm, '<ul><li>$1</li></ul>')
      .replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2">$1</a>')
      .replace(/!\[(.*?)\]\((.*?)\)/g, '<img alt="$1" src="$2">');
  }

  // 关于页面的事件处理
  aboutIcon.addEventListener('click', () => {
    aboutModal.style.display = 'block';
    loadReadme();
  });

  aboutCloseBtn.addEventListener('click', () => {
    aboutModal.style.display = 'none';
  });

  aboutModal.addEventListener('click', (e) => {
    if (e.target === aboutModal) {
      aboutModal.style.display = 'none';
    }
  });

  // 设置页面标题
  const authorInfo = getAuthorInfo();
  document.title = '股市行情助手 - ' + authorInfo.email+' '+authorInfo.name;
}); 

/**
 * 初始化拖拽排序功能
 */
function initDragAndDrop() {
  const stockList = document.getElementById('stock-list');
  const dragHandles = document.querySelectorAll('.drag-handle');

  dragHandles.forEach(handle => {
    handle.addEventListener('mousedown', function(e) {
      const stockItem = this.closest('.stock-item');
      draggedItem = stockItem;
      draggedItemIndex = Array.from(stockList.children).indexOf(stockItem);
      
      stockItem.classList.add('dragging', 'dragging-start');
      
      const rect = stockItem.getBoundingClientRect();
      const offsetY = e.clientY - rect.top;
      
      // 鼠标移动事件处理
      function onMouseMove(e) {
        const y = e.clientY - offsetY;
        draggedItem.style.position = 'fixed';
        draggedItem.style.top = y + 'px';
        draggedItem.style.width = rect.width + 'px';
        
        const targetItem = getTargetItem(e.clientY);
        if (targetItem && targetItem !== draggedItem) {
          const targetIndex = Array.from(stockList.children).indexOf(targetItem);
          if (targetIndex < draggedItemIndex) {
            stockList.insertBefore(draggedItem, targetItem);
          } else {
            stockList.insertBefore(draggedItem, targetItem.nextSibling);
          }
          draggedItemIndex = Array.from(stockList.children).indexOf(draggedItem);
        }
      }
      
      // 鼠标释放事件处理
      function onMouseUp() {
        draggedItem.classList.remove('dragging', 'dragging-start');
        draggedItem.style.position = '';
        draggedItem.style.top = '';
        draggedItem.style.width = '';
        draggedItem = null;
        
        saveNewOrder();
        
        document.removeEventListener('mousemove', onMouseMove);
        document.removeEventListener('mouseup', onMouseUp);
      }
      
      document.addEventListener('mousemove', onMouseMove);
      document.addEventListener('mouseup', onMouseUp);
    });
  });
}

/**
 * 获取拖拽目标位置的元素
 * @param {number} y 鼠标Y坐标
 * @returns {HTMLElement} 目标元素
 */
function getTargetItem(y) {
  const stockItems = document.querySelectorAll('.stock-item:not(.dragging)');
  return Array.from(stockItems).reduce((closest, item) => {
    const box = item.getBoundingClientRect();
    const offset = y - box.top - box.height / 2;
    
    if (offset < 0 && offset > closest.offset) {
      return { offset, element: item };
    } else {
      return closest;
    }
  }, { offset: Number.NEGATIVE_INFINITY }).element;
}

/**
 * 保存新的股票列表顺序
 */
function saveNewOrder() {
  const stockItems = document.querySelectorAll('.stock-item');
  const newOrder = Array.from(stockItems).map(item => {
    const code = item.dataset.code;
    const name = item.querySelector('.stock-info div div:first-child').textContent;
    return { code, name };
  });
  
  saveStockList(newOrder, () => {
    console.log('新的排序已保存');
  });
} 

/**
 * 获取作者信息
 * @returns {Object} 包含作者姓名、邮箱和URL的对象
 */
function getAuthorInfo() {
  return {
    name: '唐晓军',
    email: '417281862@qq.com',
    url: 'https://gitee.com/codecomb'
  };
}
